<template>
  <div class="app-container">
    <div class="page-header">
      <div class="header-left">
        <el-button
          link
          type="primary"
          icon="Back"
          @click="handleBack"
          class="back-button"
        >
          返回
        </el-button>
        <h2 class="page-title">任务详情</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" icon="Edit" @click="handleEdit"
          >编辑任务</el-button
        >
        <el-button type="success" icon="Download" @click="handleDownload"
          >下载模型</el-button
        >
        <el-button type="warning" icon="Upload" @click="handleDeploy"
          >部署模型</el-button
        >
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-loading="loading" class="loading-container">
      <!-- 任务基本信息 -->
      <div class="info-section">
        <h3 class="section-title">基本信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="任务ID">
            <el-tag type="info">{{ taskInfo.task_id || "-" }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="任务名称">
            {{ taskInfo.task_name || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="任务状态">
            <el-tag :type="getStatusType(taskInfo.task_status)">
              {{ taskInfo.task_status || "-" }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ parseTime(taskInfo.create_time) || "-" }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 任务进度信息 -->
      <div class="progress-section">
        <h3 class="section-title">任务进度</h3>
        <div class="progress-info">
          <div class="progress-item">
            <div class="progress-label">总体进度</div>
            <div class="progress-content">
              <el-progress
                :percentage="getOverallProgress()"
                :status="getProgressStatus(getOverallProgress())"
                :stroke-width="8"
              />
            </div>
          </div>
          <div class="progress-stats">
            <div class="stat-item">
              <div class="stat-number">{{ getProgressStats().total }}</div>
              <div class="stat-label">总任务数</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ getProgressStats().completed }}</div>
              <div class="stat-label">已完成</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ getProgressStats().running }}</div>
              <div class="stat-label">运行中</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ getProgressStats().failed }}</div>
              <div class="stat-label">失败</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 算法执行详情 -->
      <div class="algorithm-section">
        <h3 class="section-title">算法执行详情</h3>
        <el-table :data="algorithmDetails" style="width: 100%" stripe>
          <el-table-column prop="algorithmName" label="算法名称" width="180" />
          <el-table-column prop="progress" label="进度" width="200">
            <template #default="scope">
              <el-progress
                :percentage="scope.row.progress"
                :status="getProgressStatus(scope.row.progress)"
                :stroke-width="6"
              />
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="120">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="开始时间" width="180">
            <template #default="scope">
              {{ parseTime(scope.row.startTime) || "-" }}
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间" width="180">
            <template #default="scope">
              {{ parseTime(scope.row.updateTime) || "-" }}
            </template>
          </el-table-column>
          <el-table-column prop="duration" label="耗时" width="120">
            <template #default="scope">
              {{ scope.row.duration || "-" }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="viewLogs(scope.row)"
                :disabled="!scope.row.hasLogs"
              >
                查看日志
              </el-button>
              <el-button
                link
                type="success"
                size="small"
                @click="downloadResult(scope.row)"
                :disabled="scope.row.status !== '已完成'"
              >
                下载结果
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 训练日志 -->
      <div class="logs-section" v-if="showLogs">
        <h3 class="section-title">训练日志</h3>
        <div class="logs-container">
          <el-input
            v-model="trainingLogs"
            type="textarea"
            :rows="15"
            readonly
            placeholder="暂无日志信息"
            class="logs-textarea"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="TrainingDetail">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { parseTime } from "@/utils/ruoyi";
import { getTrainingTask, downloadTrainingModel } from "@/api/training";

const route = useRoute();
const router = useRouter();

const loading = ref(false);
const showLogs = ref(false);
const trainingLogs = ref("");

// 任务基本信息
const taskInfo = ref({
  task_id: "",
  task_name: "",
  task_status: "",
  create_time: "",
});

// 算法执行详情数据（模拟数据，实际项目中应该从API获取）
const algorithmDetails = ref([
  {
    algorithmName: "数据预处理",
    progress: 100,
    status: "已完成",
    startTime: "2024-03-20 09:00:00",
    updateTime: "2024-03-20 09:15:00",
    duration: "15分钟",
    hasLogs: true,
  },
  {
    algorithmName: "特征工程",
    progress: 100,
    status: "已完成",
    startTime: "2024-03-20 09:15:00",
    updateTime: "2024-03-20 09:45:00",
    duration: "30分钟",
    hasLogs: true,
  },
  {
    algorithmName: "模型训练",
    progress: 75,
    status: "运行中",
    startTime: "2024-03-20 09:45:00",
    updateTime: "2024-03-20 10:30:00",
    duration: "45分钟",
    hasLogs: true,
  },
  {
    algorithmName: "模型验证",
    progress: 0,
    status: "等待中",
    startTime: "",
    updateTime: "",
    duration: "",
    hasLogs: false,
  },
]);

// 返回上一页
function handleBack() {
  router.push("/model/training");
}

// 编辑任务
function handleEdit() {
  // 可以打开编辑弹窗或跳转到编辑页面
  ElMessage.info("编辑功能正在开发中");
}

// 下载模型
async function handleDownload() {
  try {
    const response = await downloadTrainingModel(taskInfo.value.task_id);

    // 创建下载链接
    const blob = new Blob([response.data]);
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = `model_${taskInfo.value.task_id}.zip`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    ElMessage.success("开始下载模型");
  } catch (error) {
    console.error("下载模型失败:", error);
    ElMessage.error("下载模型失败");
  }
}

// 部署模型
function handleDeploy() {
  ElMessage.info("部署功能正在开发中");
}

// 获取状态标签类型
function getStatusType(status) {
  switch (status) {
    case "运行中":
      return "primary";
    case "已完成":
      return "success";
    case "失败":
      return "danger";
    case "等待中":
      return "info";
    default:
      return "info";
  }
}

// 获取进度状态
function getProgressStatus(progress) {
  if (progress === 100) return "success";
  if (progress > 0) return "";
  return "exception";
}

// 获取总体进度
function getOverallProgress() {
  if (algorithmDetails.value.length === 0) return 0;
  const totalProgress = algorithmDetails.value.reduce(
    (sum, item) => sum + item.progress,
    0
  );
  return Math.round(totalProgress / algorithmDetails.value.length);
}

// 获取进度统计
function getProgressStats() {
  const total = algorithmDetails.value.length;
  const completed = algorithmDetails.value.filter(
    (item) => item.status === "已完成"
  ).length;
  const running = algorithmDetails.value.filter(
    (item) => item.status === "运行中"
  ).length;
  const failed = algorithmDetails.value.filter(
    (item) => item.status === "失败"
  ).length;

  return { total, completed, running, failed };
}

// 查看日志
function viewLogs(row) {
  showLogs.value = true;
  trainingLogs.value =
    `=== ${row.algorithmName} 执行日志 ===\n\n` +
    `开始时间: ${row.startTime}\n` +
    `当前状态: ${row.status}\n` +
    `执行进度: ${row.progress}%\n\n` +
    `[${new Date().toLocaleString()}] 开始执行${row.algorithmName}...\n` +
    `[${new Date().toLocaleString()}] 加载数据完成\n` +
    `[${new Date().toLocaleString()}] 参数初始化完成\n` +
    `[${new Date().toLocaleString()}] 正在执行算法逻辑...\n` +
    `[${new Date().toLocaleString()}] 当前进度: ${row.progress}%\n`;

  if (row.status === "已完成") {
    trainingLogs.value +=
      `[${new Date().toLocaleString()}] 执行完成\n` +
      `[${new Date().toLocaleString()}] 结果保存成功\n`;
  }

  // 滚动到日志区域
  setTimeout(() => {
    const logsSection = document.querySelector(".logs-section");
    if (logsSection) {
      logsSection.scrollIntoView({ behavior: "smooth" });
    }
  }, 100);
}

// 下载结果
function downloadResult(row) {
  ElMessage.success(`开始下载${row.algorithmName}的执行结果`);
}

// 获取任务详情
async function fetchTaskDetail(taskId) {
  loading.value = true;
  try {
    const response = await getTrainingTask(taskId);
    const taskDetail = response.data || response;

    // 更新任务信息
    taskInfo.value = {
      task_id: taskDetail.task_id || taskId,
      task_name: taskDetail.task_name || "未知任务",
      task_status: taskDetail.task_status || "未知状态",
      create_time: taskDetail.create_time || "",
    };

    // 根据任务状态更新算法详情（模拟逻辑）
    updateAlgorithmDetailsByStatus(taskDetail.task_status);
  } catch (error) {
    console.error("获取任务详情失败:", error);
    ElMessage.error("获取任务详情失败");

    // 使用路由参数作为备用数据
    taskInfo.value = {
      task_id: taskId,
      task_name: "获取失败",
      task_status: "未知",
      create_time: "",
    };
  } finally {
    loading.value = false;
  }
}

// 根据任务状态更新算法详情
function updateAlgorithmDetailsByStatus(status) {
  if (status === "已完成") {
    algorithmDetails.value.forEach((item) => {
      item.progress = 100;
      item.status = "已完成";
    });
  } else if (status === "运行中") {
    // 保持当前的进度分布
  } else if (status === "暂停中") {
    algorithmDetails.value.forEach((item) => {
      if (item.progress > 0 && item.progress < 100) {
        item.status = "暂停中";
      }
    });
  }
}

onMounted(() => {
  // 从路由参数中获取任务ID
  const taskId = route.params.id;
  if (!taskId) {
    ElMessage.error("任务ID不存在");
    router.push("/model/training");
    return;
  }

  // 获取任务详情
  fetchTaskDetail(taskId);
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-right {
  display: flex;
  gap: 10px;
}

.back-button {
  margin-right: 10px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.loading-container {
  min-height: 400px;
}

.info-section,
.progress-section,
.algorithm-section,
.logs-section {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.progress-info {
  display: flex;
  gap: 30px;
  align-items: center;
}

.progress-item {
  flex: 1;
}

.progress-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.progress-content {
  width: 100%;
}

.progress-stats {
  display: flex;
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 6px;
  min-width: 80px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.logs-container {
  margin-top: 10px;
}

.logs-textarea {
  font-family: "Consolas", "Monaco", monospace;
}

.logs-textarea :deep(.el-textarea__inner) {
  background-color: #1e1e1e;
  color: #d4d4d4;
  border: 1px solid #404040;
  font-family: "Consolas", "Monaco", monospace;
  font-size: 12px;
  line-height: 1.4;
}
</style>
